package cn.com.pansky.service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import net.vsame.url2sql.action.CommonAction;
import net.vsame.url2sql.helper.SqlHelper;
import net.vsame.url2sql.sql.Model;

import org.apache.commons.lang3.StringUtils;

import cn.com.pansky.action.bank.JHQueryOrder;
import cn.com.pansky.action.bank.PSBCAction;
import cn.com.pansky.payment.PayConf;
import cn.com.pansky.sdk.API;
import cn.com.pansky.util.DateUtil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class OrderService extends CommonAction{
	
	private String ca006;
	private String aae011;
	

	public String getAae011() {
		return aae011;
	}

	public void setAae011(String aae011) {
		this.aae011 = aae011;
	}

	public String getCa006() {
		return ca006;
	}

	public void setCa006(String ca006) {
		this.ca006 = ca006;
	}

	/**
	 * 已支付订单查询
	 * @param json
	 * @param userid
	 */
	public void dealOrder(JSONObject json, String userid) {
		
		JSONObject param = new JSONObject();
		param.put("AAA121", "QPAIDA20020"); //业务类型
		param.put("AAZ288", context.getParam("AAZ288")); // 订单号
		param.put("AAC002", "QPAIDA20020"); // 订单号
		JSONObject object = API.sendController("queryProxyPayController.json", param);
		handleResult(object);
	}
	
	/**
	 * 未支付订单查询
	 * @param json
	 * @param userid
	 * @throws UnsupportedEncodingException 
	 */
	public void unDealOrder(String CA006){
		
		JSONObject param = new JSONObject();
		param.put("AAA121", "QUNPAIDA20020"); //业务类型
		param.put("AAC002", CA006); // 订单号
		param.put("AAC147", CA006); // 订单号
		param.put("AAE011", user.getString("AA001")); // 代理人ID
		JSONObject object = API.sendController("queryUNPayController.json", param);
		if(object.getBooleanValue("SUCCESS")) {
					
			JSONArray array = object.getJSONArray("MSG");
			JSONObject json = (JSONObject)array.get(0);
			context.getServletSession().setAttribute("orderWriteCA006", CA006); // 根据CA001获取到CA006存入session
			context.getServletSession().setAttribute("BAB502", json.getString("BAB502"));
			context.getServletSession().setAttribute("AAE051", json.getString("AAE051"));
			
			this.setCa006(CA006);
			this.setAae011(((Model)context.getSessionVal("user")).getString("AA001"));
			
			String orderNumber = json.getString("AAZ288");
			String BAB502 = json.getString("BAB502"); // 支付银行类别
			Boolean orderStatus = checkOrderStatus(orderNumber, BAB502, json.getString("AAE051")); //查询银行支付结果
			if(orderStatus) { //如果银行支付成功，且回填业务系统成功。则不再有未支付订单。
				datas.put("isPass", false);
			}else{
					
				String newAaz289 = getYCNewOrderNum(json.getString("AAZ288"), BAB502);
				json.put("AAZ288", newAaz289);
					
				datas.put("isPass", true);
				datas.put("datas", json);
			}
		}else{
			datas.put("isPass", false);
			datas.put("info", object.getString("MSG"));
	    }
		context.getDatas().put("result", datas);
	}

	/**
	 * 如果银行是邮储，重新组装订单号
	 * @param aaz288
	 * @param bab502
	 * @return
	 */
	private String getYCNewOrderNum(String aaz288, String bab502) {
		String newAaz289 = aaz288;
		if("YC".equals(bab502)) {
			
			//邮储订单号从数据库查询
			String sql = "update yc01 set aaz289 = ? where aaz288 = ?";
			newAaz289 = aaz288+DateUtil.current7Time();
			SqlHelper.execute(sql, newAaz289, aaz288);
		}
		return newAaz289;
	}

	/**
	 * 查询银行支付结果，如果银行支付成功，回填业务系统
	 * @param orderNumber
	 * @param BAB502
	 * @return
	 */
	private Boolean checkOrderStatus(String orderNumber, String BAB502, String AAE051) {
		if("YC".equals(BAB502)) {
			getYCOrderNum(orderNumber);
		}
		
		//查询订单状态：
//		OrderService os = new OrderService();
		Boolean orderStatus = this.orderQuery(BAB502, orderNumber, AAE051);
		return orderStatus;
	}
	
	/**
	 * 历史订单查询
	 * @param json
	 * @param CA006
	 */
	public void hisOrder(String userId) {
		int page = 1;
		if(null != context.getParam("PAGE")) {
			page = Integer.parseInt(context.getParam("PAGE"));
		}
		//AAC147 证件号码
		JSONObject param = new JSONObject();
		param.put("AAA121", "QPROXYA20020"); //业务类型
		param.put("AAC002", "14262219920107153x"); // 订单号
		param.put("AAE011", userId); // 代理人ID
		param.put("PAGE", page); // 代理人ID
		param.put("PAGESIZE", 10); // 记录数
		JSONObject object = API.sendController("queryProxyPayController.json", param);
//		handleResult(object);
		if(object.getBooleanValue("SUCCESS")) {
			JSONArray array = object.getJSONArray("MSG");
			JSONArray newArray = new JSONArray();
			if(array.size()>0) {
				for(int i=0; i<array.size(); i++) {
					JSONObject obj = array.getJSONObject(i);
					if("0".equals(obj.getString("AAE016")) && "1".equals(obj.getString("AAE100"))){
						String bab502 = obj.getString("BAB502");
						String orderNumber = obj.getString("AAZ288");
						String AAE051 = obj.getString("AAE051");
						Boolean orderStatus = checkOrderStatus(orderNumber, bab502, AAE051); //查询银行支付结果
						if(orderStatus) {
							obj.put("AAE016", "1"); //如果支付成功，且回填订单状态成功，更新订单状态为已支付
							newArray.add(obj);
						}else{ //如果未支付成功，且是邮储
							String newAaz289 = getYCNewOrderNum(orderNumber, bab502);
							obj.put("AAZ288", newAaz289);
						}
					}
					newArray.add(obj);
				}
			}
			datas.put("datas", newArray);  //使用更新后的订单信息
			datas.put("isPass", true);
		}else{
			datas.put("isPass", false);
			datas.put("info", object.getString("MSG"));
		}
		context.getDatas().put("result", datas);
	}

	private void getYCOrderNum(String orderNumber) {
		//邮储订单号从数据库查询
		String sql = "select * from yc01 where aaz288 = ?";
		Model m = SqlHelper.queryOne(sql, orderNumber);
		if(m != null) {
			orderNumber = m.getString("AAZ289");
		}
	}
	
	/**
	 * 取消订单
	 * @param json
	 * @param CA006
	 */
	public void cancleOrder(String AAZ288) {
		
		Model user = (Model) context.getServletSession().getAttribute("user");
		JSONObject param = new JSONObject();
		param.put("AAA121", "RA2002002"); //业务类型
		param.put("AAZ288", AAZ288); // 订单号
		param.put("AAC002", "RA2002002"); // 订单号
		param.put("AAE011", user.getString("AA001")); // 代理人ID
		JSONObject object = API.sendController("paymentRevokeController.json", param);
		JSONObject data = new JSONObject();
		data.put("isPass", object.getBooleanValue("SUCCESS"));
		data.put("info", object.getString("MSG"));
		if(object.getBooleanValue("SUCCESS")){
			
			data.put("info", "取消订单成功");
		}
		context.getDatas().put("result", data);
		
	}
	
	
	/**
	 * 支付成功，回填业务系统数据
	 * @param args
	 */
	
	public void orderBackWrite(Map<String, String> map) {
		
		JSONObject param = new JSONObject();
		Model user = (Model) context.getServletSession().getAttribute("user");
		param.put("AAA121", "A2002003"); // 缴费标识
		param.put("AAC002", context.getSessionVal("orderWriteCA006")); // 身份证号
		param.put("AAZ065", map.get("bankType")); // 银行ID
		param.put("AAE010", map.get("AAE010")); // 当事人缴费账号
		param.put("AAE074", map.get("AcqSsn")); // 银行缴费流水号
		param.put("AAE022", map.get("TranAmt")); // 缴费金额
		param.put("AAZ288", map.get("TermSsn")); // 社保流水号
		param.put("AAE011", user.getString("AA001")); // 代理人ID
		// 调用核心业务接口，传入账户信息进行回填订单
		JSONObject object = API.sendController("paymentController.json", param);
		datas.put("isPass", object.getBoolean("SUCCESS"));
		datas.put("info", object.getString("MSG"));
	}
	
	/**
	 * 处理结果
	 * @param obj
	 */
	protected void handleResult(JSONObject obj) {
		if(obj.getBooleanValue("SUCCESS")) {
			JSONArray array = obj.getJSONArray("MSG");
			datas.put("datas", array);
			datas.put("isPass", true);
		}else{
			datas.put("isPass", false);
			datas.put("info", obj.getString("MSG"));
		}
		context.getDatas().put("result", datas);
	}
	
	/**
	 * 根据订单号查询是否已支付状态，如果已支付返回true,否则返回false
	 * 农行支付自动返回商户
	 */
	public static boolean checkOrderStauts(String orderNumber) {
		JSONObject param = new JSONObject();
		param.put("AAA121", "QPAIDA20020"); //业务类型
		param.put("AAZ288", orderNumber); // 订单号
		param.put("AAC002", "QPAIDA20020"); // 订单号
		JSONObject object = API.sendController("queryProxyPayController.json", param);
		boolean sign = false;
		if(object.getBooleanValue("SUCCESS")) {
			JSONArray array = object.getJSONArray("MSG");
			for(int i = 0; i < array.size(); i++) {
				JSONObject obj = JSONObject.parseObject(array.get(i).toString());
				if(obj.getString("AAE016").equals("1")) {
					sign = true;
					break;
				}
			}
		}
		return sign;
	} 
	
	
	/**
	 * 回填业务系统
	 * @param json
	 */
	public Boolean writeBisness(JSONObject json, String aae001, String ca006) {
		// 回填业务系统数据
		OrderBackWriteService os = new OrderBackWriteService();
		Map<String, String> map = new HashMap<String, String>();
		String orderAmount = json.getString("orderAmount");
		// 将支付金额分转元
		BigDecimal amount = new BigDecimal(orderAmount);
		if("JH".equals(json.getString("bankType"))){
			
			amount = amount.divide(new BigDecimal(100));
		}
		map.put("AAE010", json.getString("AAE010")); // 当事人缴费账号
		map.put("bankType", json.getString("bankType"));
		map.put("AcqSsn", json.getString("qid"));// 银行缴费流水号
		map.put("TranAmt", amount.toString());// 缴费金额  //
		map.put("TermSsn", json.getString("orderNumber"));// 社保流水号
//		map.put("AAC002", ca006);//身份证号
		map.put("AAC002", "");
//		map.put("AAC002", (String)context.getSessionVal("orderWriteCA006"));//身份证号
//		map.put("AAE011", ((Model)context.getSessionVal("user")).getString("AA001"));//代理人ID
		map.put("AAE011", aae001);//代理人ID
		JSONObject obj = os.orderBackWrite(map);
//		context.getDatas().put("isPass", obj.getBooleanValue("SUCCESS"));
		return obj.getBooleanValue("SUCCESS");
	}
	
	/**
	 * 订单状态查询
	 * @param os
	 * @param BAB502 银行类别
	 * @param orderNumber 订单号
	 * @throws UnsupportedEncodingException
	 */
	public Boolean orderQuery(String BAB502, String orderNumber, String AAE051){
		Boolean retVal = false ;
		OrderService os = new OrderService();
		JSONObject json = new JSONObject();
//		json.put("cardId", cardId);
		System.out.println("开始查询订单状态");
		if(BAB502 != null && BAB502.equals("JH")) {
			String queryurl = PayConf.JSPT_QUERY_URL;
			String merId = PayConf.MERID;
			String signKey = PayConf.SIGNKEY;
			String queryTime = StringUtils.trimToEmpty(DateUtil.currentTime());
			String qid = "";
			context.getDatas().put("isPass", false);
			JHQueryOrder queryOrder = new JHQueryOrder(queryurl, merId, signKey, orderNumber, queryTime, qid);
			json = queryOrder.query();
		} else if(BAB502 != null && BAB502.equals("YC")) {
			PSBCAction psbc = new PSBCAction();
			json = psbc.psbcOrderQuery(orderNumber, AAE051);
		} else if(BAB502 != null && BAB502.equals("NH")) {
			ABCQuery query = new ABCQuery();
			json = query.query(orderNumber, AAE051);
		}
		if(json != null) {
			if("1".equals(json.getString("state"))) { //支付成功回填业务系统
				retVal = os.writeBisness(json, this.getAae011(), this.getCa006());
			}
		}
		return retVal;
	}

	
	public void wxOrderQuery() {
		String appid = "";   //应用APPID	
		String mch_id = "";  //商户 ID 
//		String transaction_id = "";  //微信订单号
		String out_trade_no = "";  //商户订单号
		String nonce_str = UUID.randomUUID().toString(); // 随机数
		String sign = "";
		
		
		
		
	}
	
	public static void main(String[] args) {
		JSONObject param = new JSONObject();
		param.put("AAA121", "QPAIDA20020"); //业务类型
		param.put("AAZ288", "17427255"); // 订单号
		param.put("AAC002", "QPAIDA20020"); // 订单号
		JSONObject object = API.sendController("queryProxyPayController.json", param);
		System.out.println(object);
		boolean sign = false;
		if(object.getBooleanValue("SUCCESS")) {
			JSONArray array = object.getJSONArray("MSG");
			for(int i = 0; i < array.size(); i++) {
				JSONObject obj = JSONObject.parseObject(array.get(i).toString());
				if(obj.getString("AAE016").equals("1")) {
					sign = true;
					break;
				}
			}
		}
		System.out.println(sign);
	}
	
	
}
